package com.wanghangcloud.common.config;

import cn.hutool.json.JSONUtil;
import com.wanghangcloud.common.bean.Result;
import com.wanghangcloud.common.bean.ResultCode;
import com.wanghangcloud.common.exception.BusinessException;
import feign.Response;
import feign.codec.ErrorDecoder;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * feign调用错误解析
 */
public class CustomErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.body() != null) {
            try (InputStream inputStream = response.body().asInputStream()){
                Result result = JSONUtil.toBean(new String(inputStream.readAllBytes(), StandardCharsets.UTF_8), Result.class);
                return new BusinessException(result.getCode(), result.getMsg());
            } catch (Exception e) {
                return new RuntimeException(e);
            }
        }

        // 默认处理
        return defaultErrorDecoder.decode(methodKey, response);
    }

    private String getMsg(Response response) {
        try {
            if (response.body() != null) {
                return JSONUtil.parseObj(new String(
                        response.body().asInputStream().readAllBytes(),
                        StandardCharsets.UTF_8
                )).getStr("msg");
            }
        } catch (Exception e) {
            return ResultCode.SYSTEM_ERROR.getMsg();
        }
        return ResultCode.SYSTEM_ERROR.getMsg();
    }
}
